﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Kooboo.CMS.CustomSettingSyncWrapper.Controllers
{
    using System.Web.Mvc;
    using Kooboo.CMS.Sites.Models;
    using Kooboo.CMS.Sites.Services;
    using Kooboo.CMS.Web.Areas.Sites.Controllers;

    public class CustomSettingController : AdminControllerBase
    {
        #region SyncAdd

        [HttpPost]
        public JsonResult SyncAdd(string siteName, string key, string value)
        {
            SyncAddToSubSites(new Site(siteName), key, value);

            return Json(new {
                Succ = true
            });
        }

        private void SyncAddToSubSites(Site site, string key, string value)
        {
            SaveCustomSetting(site, key, value);

            foreach (var subSite in ServiceFactory.SiteManager.ChildSites(site))
            {
                SyncAddToSubSites(subSite, key, value);
            }
        }

        private void SaveCustomSetting(Site site, string key, string value)
        {
            site = site.AsActual();

            if (site.CustomFields.ContainsKey(key))
            {
                if (string.IsNullOrEmpty(value) == false)
                {
                    site.CustomFields[key] = value;
                }
            }
            else
            {
                site.CustomFields[key] = value;
            }

            ServiceFactory.SiteManager.Update(site);
        }

        #endregion

        #region SyncDelete

        [HttpPost]
        public JsonResult SyncDelete(string siteName, string key)
        {
            SyncDeleteFromSubSites(new Site(siteName), key);

            return Json(new
            {
                Succ = true
            });
        }

        private void SyncDeleteFromSubSites(Site site, string key)
        {
            DeleteCustomSetting(site, key);

            foreach (var subSite in ServiceFactory.SiteManager.ChildSites(site))
            {
                SyncDeleteFromSubSites(subSite, key);
            }
        }

        private void DeleteCustomSetting(Site site, string key)
        {
            site = site.AsActual();

            if (site.CustomFields.ContainsKey(key))
            {
                site.CustomFields.Remove(key);
            }

            ServiceFactory.SiteManager.Update(site);
        }

        #endregion
    }
}
